package com.las.nogu.controller;

import com.alibaba.fastjson.JSONObject;
import com.las.nogu.commond.Constant;
import com.utils.RedisUtils;
import com.utils.osu.OsuApi2;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;

@Controller
@RequestMapping("/")
public class IndexController {

    private final Log log = LogFactory.getLog(IndexController.class);

    @RequestMapping("/")
    public String index() {
        return "/templates/home.html";
    }

    @RequestMapping("/search")
    public String search() {
        return "/templates/search.html";
    }

    @RequestMapping("/osucup")
    public String osucup() {
        return "/templates/osucup.html";
    }

    @RequestMapping("/mio")
    public String collation() {
        return "/templates/collation.html";
    }

    @RequestMapping("/shopping")
    public String chat() {
        return "/templates/notice.html";
    }


    @ResponseBody
    @RequestMapping("/getUserInfo")
    public Object getUserInfo(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if ("osuSessionId".equals(cookie.getName())) {
                    //找到了key，把value取出来
                    String osuSessionId = URLDecoder.decode(cookie.getValue(), "UTF-8");
                    Object obj = session.getAttribute(osuSessionId);
                    if (null != obj) {
                        String sId = obj.toString();
                        if (sId.equals(session.getId())) {
                            // 说明当初授权登录放入的cookie是同一个会话，并且没有过期
                            log.debug("当前用户会话ID和cookie中存入的会话ID一致");
                            return session.getAttribute(Constant.USER_INFO);
                        } else {
                            // 这种情况就是用户关闭浏览器，再开启新的浏览器是新的会话session
                            return getObjectAgain(session, osuSessionId);
                        }
                    } else {
                        return getObjectAgain(session, osuSessionId);
                    }
                }
            }
        }
        // 第一次cookie是没有的，那查找下会话中的userInfo，若还没有，就完全是没授权，需要提示用户登录OSU
        log.debug("第一次cookie是没有的,需要提示用户登录OSU");
        return session.getAttribute(Constant.USER_INFO);
    }

    private Object getObjectAgain(HttpSession session, String osuSessionId) {
        // 这种情况就是用户关闭浏览器，再开启新的浏览器是新的会话session
        log.debug("当前用户会话ID和cookie中存入的会话ID不一致");
        String osuId = osuSessionId.split(",")[0];
        String oldSessionId = osuSessionId.split(",")[1];
        Object oldUser = RedisUtils.get(Constant.OSU_LOGIN_TAG + osuId + ":" + osuSessionId);
        if (null != oldUser) {
            session.setAttribute(Constant.USER_INFO, JSONObject.toJSONString(oldUser));
            session.setAttribute(Constant.MY_SESSION,oldSessionId);
            session.setAttribute(osuId + "," + oldSessionId, oldSessionId);
            return oldUser;
        }
        if (!RedisUtils.hasKey(Constant.OSU_AUTH_TAG + oldSessionId)) {
            // 防止有人伪造cookie
            return null;
        }
        Object authToken = RedisUtils.get(Constant.OSU_AUTH_TAG + oldSessionId);
        if (null == authToken) {
            // 有可能过期，再查一遍为空结束方法
            return null;
        }
        // 重新获取osu用户信息
        String userInfo = OsuApi2.getInstanceByToken(authToken.toString()).getMeInfo("osu");
        log.info("重新获取OSU玩家信息：" + userInfo);
        // 还是用旧的会话ID存放进去到新会话属性
        session.setAttribute(Constant.USER_INFO, userInfo);
        session.setAttribute(Constant.MY_SESSION,oldSessionId);
        session.setAttribute(osuId + "," + oldSessionId, oldSessionId);
        return session.getAttribute(Constant.USER_INFO);
    }

}
